#include <stdio.h>
#include "magic.h"

Status magic(int *list,int row,int col)
{
	if (list == NULL){
		fprintf(stderr,"The pointer is NULL\n");
		return ERROR;
	}
	if (row != col || (row % 2 == 0)){
		fprintf(stderr,"The row must be equal to col,and they can,t be even!\n");
		return ERROR;
	}

	//ok,do it.
	int i,j;
	int count;
	for(count = 0;count < row * col;count++){
		list[count] = 0;
	}

	i = 0;
	j = (col - 1) / 2;
	list[i * row + j] = 1;

	for(count = 1;count < row * col;count++){
		int temp_i,temp_j;
		temp_i = (i - 1 < 0)?(row - 1):(i - 1);  // up
		temp_j = (j - 1 < 0)?(col - 1):(j - 1);  // left
		if (list[temp_i * row + temp_j]){
			i = (i + 1) % row;					// down
			list[i * row + j] = count + 1;
		}
		else{
			list[temp_i * row + temp_j] = count + 1;
			i = temp_i;
			j = temp_j;
		}
	}
	return OK;
}

void show_magic(int *list,int row,int col)
{
	int count;
	for(count = 0;count < row * col;count++){
		printf("%-2d",list[count]);
		printf("%s",((count + 1) % row)?" ":"\n");
	}
}

